<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="用户ID">
      <el-input v-model="pageHelper.id" placeholder="请输入用户ID" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>


  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="ID" prop="id" />
    <el-table-column label="用户名" prop="username" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改用户</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除用户</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next" :total="pageHelper.total" v-model:current-page="pageHelper.pageNum"
    v-model:page-size="pageHelper.pageSize" @current-change="getUserList" />


    <el-dialog v-model="dialogFormVisible" title="修改用户信息">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
            <el-upload class="avatar-uploader" action="" :http-request="uploadAvatar" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar" Avatar>
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="ruleForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex" class="ml-4">
                <el-radio label="男" size="large">男</el-radio>
                <el-radio label="女" size="large">女</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" />
        </el-form-item>


        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                修改
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
    
  </el-dialog>
</template>
  
<script lang="ts" setup>
import api from '@/api';
import { computed, onMounted, reactive, ref } from 'vue'
import { ElNotification, FormInstance, FormRules, UploadProps } from 'element-plus';
import store from '@/store';


const search = ref('')
const filterTableData = computed(() =>
  userList.value.filter(
    (data) =>
      !search.value ||
      data.username.toLowerCase().includes(search.value.toLowerCase())
  )
)
const handleEdit = (index: number, row: any) => {
  userId.value.id = row.id
  getUserById()
  dialogFormVisible.value = true

}
const handleDelete = (index: number, row: any) => {
  console.log(index, row)
}


const userList = ref([
  {
    username: ''
  }
])

const pageHelper = ref({
  pageNum: 1,
  pageSize: 2,
  id: '',
  total: 0

})

onMounted(() => {
  getUserList()
})

function getUserList() {
  api.user.getUserList(pageHelper.value)
    .then(response => {
      // 在这里可以处理提交成功后的逻辑
      userList.value = response.data.data.records
      pageHelper.value.total = response.data.data.total


    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
      // 在这里可以处理提交失败后的逻辑
    });
}


const formInline = reactive({
  user: '',
  region: '',
  date: '',
})

const onSubmit = () => {
  getUserList()
}

const categoryList = ref([
  {
    id: '',
    name: ''
  }
])

function getCategoryList() {
  api.shop.getCategoryList()
    .then(response => {
      categoryList.value = response.data.data
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    });
}


const dialogFormVisible = ref(false)

interface RuleForm {
  nickname: string
    avatar: string
    phoneNumber: string
    email: string
    sex: string
    age: string

}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
  nickname: '',
    avatar: '',
    phoneNumber: '',
    email: '',
    sex: '',
    age: ''
})

const rules = reactive<FormRules<RuleForm>>({
    phoneNumber: [
        {
            required: true,
            message: '请输入手机号',
            trigger: 'change',
        },
    ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.user.editUser(ruleForm.value)
            .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getUserById()
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            });

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

    return true
}

const uploadAvatar: UploadProps['httpRequest'] = (uploadFile) => {
    const file = uploadFile.file
    // 创建FormData对象
    const formData = new FormData();
    // 将上传的文件添加到FormData中
    formData.append('file', file);

    return api.user.uploadAvatar(formData)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ruleForm.value.avatar = response.data.data
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            });

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });
}


const userId = ref({
  id:''
})

function getUserById() {
    api.user.getUserById({ id: userId.value.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ruleForm.value = response.data.data

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });
}

</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
  